package org.aman.publish.util;

import com.jcraft.jsch.*;

import java.io.InputStream;

/**
 * @author DaiJG
 * @title SSHCommandUtil功能描述
 * @Date created at 2019/8/29 16:45
 * @Description
 * @since 1.0.0
 */
public class SshCmdUtil {
    public static ChannelExec getChannel(Session session){
        try {
            return (ChannelExec) session.openChannel("exec");
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int execute(Session session, final String command) {
        int returnCode = 0;
        try {
            ChannelExec channel = getChannel(session);
            channel.setCommand(command);
            channel.setInputStream(null);
            channel.connect();
            
            new SshExecRespThread(channel, CmdRespThread.INFO, null).start();
            new SshExecRespThread(channel, CmdRespThread.ERROR, null).start();
            
            while (true) {
                if (channel.isClosed()) {
                    returnCode = channel.getExitStatus();
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }
    
}
